﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.IO;


namespace Theosoft.Mobile.LibService
{
    public abstract class NetworkService
    {
        protected static readonly byte[] ENCRYPTKEY = { 68, 55, 67, 54, 70, 55, 49, 65, 49, 50, 49, 53, 51, 69, 69, 53 };
        protected static readonly byte[] ENCRYPTIV = { 53, 53, 67, 57, 51, 48, 68, 56, 50, 55, 66, 68, 65, 66, 70, 68 };
        protected static NetworkDAC dac = null;
        protected string curURL = null;
        internal const string APIurl = "http://www.theosoft.net/";

        public EventHandler<objEventArgs> Completed { get; set; }

        public NetworkService()
        {
            if (dac == null)
            {
                dac = new NetworkDAC(new EventHandler(ProcessResponse));
            }
        }

        protected void ProcessResponse(object sender, EventArgs e)
        {
            Debug.WriteLine("Process response.");
            byte[] buffer = (byte[])((objEventArgs)e).msg;
            buffer = unPackResponse(buffer);

            onProcessResponse(buffer);
        }

        protected abstract void onProcessResponse(byte[] buffer);

        protected byte[] unPackResponse(byte[] raw)
        {
            byte[] buffer = raw;

            //Debug.WriteLine("Decrypt response.");
            //buffer = AESEncrypt.Decrypt(buffer, ENCRYPTKEY, ENCRYPTIV);

            //Debug.WriteLine("Unzip response.");
            //using (MemoryStream ms = new MemoryStream())
            //using (var gZipStream = new GZipInputStream(new MemoryStream(buffer)))
            //{
            //    byte[] buf = new byte[1024];
            //    int len;
            //    while ((len = gZipStream.Read(buf, 0, buf.Length)) > 0)
            //    {
            //        ms.Write(buf, 0, len);
            //    }
            //    buffer = ms.ToArray();
            //}

            return buffer;
        }
    }
}
